import 'package:flutter/material.dart';
import 'package:ninetyfour/l10n/app_localizations.dart';
import '../../manger/network_utils.dart';
import '../../models/account_ye_model.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
import '../view/accoun_bottom_view.dart'; // 导入底部视图
import '../../main.dart';
import '../../class/controller/product_detail.dart';
import '../../components/toast_utils.dart';

class AccountChongPage extends StatefulWidget {
  const AccountChongPage({super.key});

  @override
  State<AccountChongPage> createState() => _AccountChongPageState();
}

class _AccountChongPageState extends State<AccountChongPage> {
  List<GroupClassModel>? groupleList = [];
  bool isEditing = false; // 用于控制是否处于编辑状态
  List<List<bool>> selectedItems = []; // 记录每个section中每个item是否被选中
  bool allSelected = false; //是否全选
  int selectedCount = 0; // 记录选中的数量

  Future<void> loadList() async {
    final response = await NetworkUtils.get(
      isSimplifiedChinese() ? RequestCmd.listGroup : RequestCmd.listGroupen,
    );

    final model = GroupDataModel.fromJson(response);

    if (model.code == 200) {
      setState(() {
        groupleList = model.data;
        selectedItems = List.generate(groupleList!.length, (sectionIndex) {
          return List.generate(groupleList![sectionIndex].data.length, (itemIndex) => false);
        });
      });
    }
  }

  // 修改toggleSelection方法，支持每个section的选中状态更新
  void toggleSelection(int sectionIndex, int itemIndex) {
    setState(() {
      // 更新指定 section 和 item 的选中状态
      selectedItems[sectionIndex][itemIndex] = !selectedItems[sectionIndex][itemIndex];
      calculateSelectedCount();
    });
  }

  void toggleSelectAll() {
    setState(() {
      // 如果全选，设置所有项为未选中；如果没有全选，设置所有项为选中
      if (allSelected) {
        // 全选状态下，取消所有选中
        selectedItems = selectedItems.map((section) {
          return section.map((item) => false).toList();
        }).toList();
      } else {
        // 非全选状态下，设置所有为选中
        selectedItems = selectedItems.map((section) {
          return section.map((item) => true).toList();
        }).toList();
      }
      allSelected =!allSelected;
      calculateSelectedCount();

    });
  }

  void calculateSelectedCount() {
    int count = 0;
    for (var section in selectedItems) {
      count += section.where((item) => item).length;
    }
    setState(() {
      selectedCount = count;
    });
  }

  void deleteAccount() async {
    if (selectedCount == 0) {
      return;
    }
    
    List<int> selectedIds = [];
    for (int sectionIndex = 0; sectionIndex < selectedItems.length; sectionIndex++) {
      for (int itemIndex = 0; itemIndex < selectedItems[sectionIndex].length; itemIndex++) {
        if (selectedItems[sectionIndex][itemIndex]) {
          selectedIds.add(groupleList![sectionIndex].data[itemIndex].id);
        }
      }
    }
    final response = await NetworkUtils.post(
      isSimplifiedChinese() ? RequestCmd.del : RequestCmd.delen,
      body: {
        'idList': selectedIds,
      },
    );
    ToastUtils.showCenterToast(context, response['msg']);
    if (response.toString().contains('200')) {
      setState(() {
        isEditing = false;
        allSelected = false;
        selectedCount = 0;
      });
      loadList();
    } 
  }

  @override
  void initState() {
    super.initState();
    loadList();
  }

  @override
  Widget build(BuildContext context) {

    return Scaffold(
      appBar: AppBar(
        toolbarHeight: 40,
        title: Text(
          AppLocalizations.of(context)!.account,
          style: const TextStyle(fontSize: 17),
        ),
        actions: [
          if (groupleList!.isNotEmpty)
          GestureDetector(
            onTap: () {
              setState(() {
                isEditing = !isEditing;
              });
            },
            child: Padding(
              padding: const EdgeInsets.only(right: 15),
              child: Text(
                isEditing ? '完成' : AppLocalizations.of(context)!.bianji,
                style: const TextStyle(fontSize: 16, color: Color(0xFF2A2A2A)),
              ),
            ),
          ),
        ],
      ),
      body: groupleList!.isEmpty
          ? Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Image.asset('assets/images/none.png'),
                  const SizedBox(height: 2),
                  Text(AppLocalizations.of(context)!.noaccount),
                ],
              ),
            )
          : ListView.builder(
            itemCount: groupleList!.length,
            itemBuilder: (context, sectionIndex) {
              return Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Padding(
                    padding: const EdgeInsets.only(left: 15, top: 15, bottom: 10),
                    child: Text(
                      groupleList![sectionIndex].categoryName,
                      style: const TextStyle(fontSize: 15, color: Color(0xFF252525)),
                    ),
                  ),
                  Container(
                    margin: const EdgeInsets.symmetric(horizontal: 15),
                    decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.circular(12),
                    ),
                    child: ListView.builder(
                      shrinkWrap: true,
                      physics: const NeverScrollableScrollPhysics(),
                      itemCount: groupleList![sectionIndex].data.length,
                      itemBuilder: (context, rowIndex) {
                        return Slidable(                
                          child: Column(
                            children: [
                              Padding(
                                padding: const EdgeInsets.symmetric(horizontal: 15, vertical: 12),
                                child: Row(
                                  children: [
                                    if (isEditing)
                                      Container(
                                        width: 34,
                                        height: 34,
                                        margin: const EdgeInsets.only(right: 8),
                                        child: Checkbox(
                                          value: selectedItems[sectionIndex][rowIndex],
                                          onChanged: (value) {
                                            toggleSelection(sectionIndex, rowIndex);
                                          },
                                          shape: CircleBorder(),
                                          materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
                                        ),
                                      ),
                                    // 文本部分，最多占满按钮左边10px空间
                                    Expanded(
                                      child: Row(
                                        children: [
                                          Flexible(
                                            child: Text(
                                              groupleList![sectionIndex].data[rowIndex].memberNumber ?? '',
                                              style: const TextStyle(fontSize: 14, color: Color(0xFF252525)),
                                              overflow: TextOverflow.ellipsis,
                                            ),
                                          ),
                                          const SizedBox(width: 6),
                                          Flexible(
                                            child: Text(
                                              groupleList![sectionIndex].data[rowIndex].memberNickName ?? '',
                                              style: const TextStyle(fontSize: 14, color: Color(0xFF252525)),
                                              overflow: TextOverflow.ellipsis,
                                            ),
                                          ),
                                        ],
                                      ),
                                    ),
                                    const SizedBox(width: 10), // 距离按钮左边10px
                                    if (!isEditing)
                                      GestureDetector(
                                        onTap: () {
                                          Navigator.push(
                                            context,
                                            MaterialPageRoute(
                                              builder: (context) => ProductDetailPage(
                                                spuId: groupleList![sectionIndex].data[rowIndex].itemId,
                                              ),
                                            ),
                                          ).then((_) {
                                            Navigator.pushAndRemoveUntil(
                                              context,
                                              MaterialPageRoute(
                                                builder: (_) => MainPage(initialIndex: 0),
                                              ),
                                              (route) => false,
                                            );
                                          });
                                        },
                                        child: Container(
                                          width: 93,
                                          height: 34,
                                          decoration: BoxDecoration(
                                            borderRadius: BorderRadius.circular(17),
                                            border: Border.all(color: const Color(0xFF5D5FEE), width: 1),
                                            color: const Color(0xFFF3F3FF),
                                          ),
                                          alignment: Alignment.center,
                                          child: Text(
                                            AppLocalizations.of(context)!.placeOrder,
                                            style: const TextStyle(color: Color(0xFF5D5FEE)),
                                          ),
                                        ),
                                      ),
                                  ],
                                )

                              ),
                              if (rowIndex < groupleList![sectionIndex].data.length - 1)
                                Padding(
                                  padding: const EdgeInsets.symmetric(horizontal: 15),
                                  child: const Divider(height: 1, color: Color(0xFFF5F5F5)),
                                ),
                            ],
                          ),
                        );
                      },
                    ),
                  ),
                ],
              );
            },
          ),
      // 添加底部视图，使用 `AccounBottomView`，并为它添加固定高度和底部安全区高度
      bottomNavigationBar: isEditing ? Padding(
        padding: EdgeInsets.only(bottom: 0),
        child: AccountBottomView(
          onSelectAll: () {  
            toggleSelectAll();
          },
          onDelete: () {     
            deleteAccount();       
          }, // 这里是你自己的删除逻辑
          isAllSelected: allSelected, // 这里是你自己的全选状态
          selectedCount: selectedCount, // 这里是你自己的选中数量
        ), // 这里是你自己创建的底部视图组件
      ) : null,
    );
  }
}
